# !/usr/bin/env python
# -*- coding: utf-8 -*-
# @File  : app.py
# @Author: dongguangwen
# @Date  : 2024-12-29 11:51
from flask import Flask, request, jsonify


def make_celery(app):
    from celery import Celery
    celery = Celery(
        app.import_name,
        backend=app.config['CELERY_RESULT_BACKEND'],
        broker=app.config['CELERY_BROKER_URL']
    )
    celery.conf.update(app.config)
    return celery


# Flask 应用初始化
app = Flask(__name__)


# celery配置
app.config.update(
    CELERY_BROKER_URL='amqp://admin:password@192.168.1.119',  # RabbitMQ
    CELERY_RESULT_BACKEND='redis://:12345678@192.168.1.119:6379/0',  # 可用 Redis、数据库等
    CELERY_INCLUDE=['tasks']  # 示例任务模块
)

# 初始化celery
celery = make_celery(app)


@app.route('/submit_task', methods=['POST'])
def submit_task():
    """提交异步任务"""
    try:
        task_data = request.json
        if not task_data:
            return jsonify({'status': 'error', 'message': 'Invalid task data.'}), 400

        from tasks import create_task
        task = create_task.delay(task_data)  # 异步执行任务
        return jsonify({'status': 'success', 'task_id': task.id}), 200
    except Exception as e:
        return jsonify({'status': 'error', 'message': str(e)}), 500


@app.route('/task_status/<task_id>', methods=['GET'])
def task_status(task_id):
    """检查任务状态"""
    from tasks import create_task
    task = create_task.AsyncResult(task_id)
    if task.state == 'PENDING':
        response = {
            'status': task.state,
            'message': 'Task is pending...'
        }
    elif task.state == 'SUCCESS':
        response = {
            'status': task.state,
            'result': task.result
        }
    elif task.state == 'FAILURE':
        response = {
            'status': task.state,
            'error': str(task.info)
        }
    else:
        response = {
            'status': task.state,
            'message': 'Task is in progress...'
        }
    return jsonify(response)


if __name__ == '__main__':
    app.run()
